/**
 * 教学班视角-课表
 * @param  {[type]} jxbTimeTable [description]
 * @return {[type]}              [description]
 */
define(function(require) {

    // 其他模块引用的对象将作为属性统一放到_module中
    var _module = {
        commonLib: require('./commonLib'),
        conflictValidator: require('./conflictValidator'),
        jxbTimeItem: require('./jxbTimeItem'),
        zeroModal: require('../../zeroModal/zeroModal')
    };

    // 缓存
    var _cache = {};

    var jxbTimeTable = {

        /**
         * 当前存储的信息
         */
        _current: {
            jxbInfo: undefined, // 当前的教学班信息
            originalArranges: undefined, // 原始的课程安排列表
            arranges: undefined, // 当前的课程安排列表
            selectedArranges: undefined, // 当前选择的课程安排
            itemToAdd: undefined, // 当前准备添加的课程的位置
            opt: undefined, // 当前的参数信息，来自manualTimeTable的params
            obstacles: undefined, // 当前的屏蔽区域
            movingArrange: undefined //当前拖拽移动的排课结果
        },

        /**
         * 刷新当前的参数信息
         * @param  {[type]} opt [description]
         * @return {[type]}     [description]
         */
        refreshCurrentOpt: function(opt) {
            this._current.opt = opt;
        },

        /**
         * 刷新当前的屏蔽区域
         * @param  {[type]} obstacles [description]
         * @return {[type]}           [description]
         */
        refreshCurrentObstacles: function(obstacles) {
            this._current.obstacles = obstacles;
            this.renderObstacles(obstacles);
        },

        /**
         * 根据教学班信息绘制星期节次表格
         * @param  {[type]} opt     [description]
         * @param  {[type]} jxbInfo [description]
         * @return {[type]}         [description]
         */
        renderWeekUnitTable: function(opt, jxbInfo) {
            this._current.opt = opt;
            this._current.jxbInfo = jxbInfo;

            var _uuid = _module.commonLib.getUuid();
            var _weeks = this.getWeeks(opt);
            var _units = this.getUnits(opt);
            var _unitMode = (typeof jxbInfo !== 'undefined' ? jxbInfo.unitMode : 1);

            var _html = '<div class="mtt_container">';
            _html += '      <table role-table-uuid="' + _uuid + '" class="mtt_table" onselectstart="return false;">';
            _html += '          ' + _module.jxbTimeItem.buildItemHtml(_weeks, _units, _unitMode);
            _html += '      </table>';
            _html += '   </div>';
            $(opt.container).html(_html);

            _module.jxbTimeItem.bindItemEvent(this);
        },

        /**
         * 渲染排课结果
         * @param  {[type]} arranges [description]
         * @return {[type]}          [description]
         */
        renderArranges: function(arranges) {
            var _this = this;

            // 清除原有的dom元素
            $('.mtt_arrange_item').remove();
            // 清除当前选中的排课结果
            this._current.selectedArrange = undefined;

            // 如果参数arranges不为空，则重新赋值
            if (arranges !== undefined) {
                this._current.arranges = arranges;
                this._current.originalArranges = _module.commonLib.deepCopy(arranges);
            }

            // 循环所有单元格
            $('[data-role="item"]').each(function() {
                var jItem = $(this);

                var item_arranges = _this.findArrangesByWeekAndUnit(jItem.attr('data-week'), jItem.attr('data-begin-unit'), jItem.attr('data-end-unit'));
                if (item_arranges.length > 0) {
                    var height = 98 / item_arranges.length;

                    for (var i = 0; i < item_arranges.length; i++) {
                        var arrange = item_arranges[i];
                        // 对排课的结果信息添加uuid唯一标识
                        if (arrange.uuid === undefined) {
                            arrange.uuid = _module.commonLib.getUuid();
                        }

                        // 判断当前排课结果是否与原始的结果一致，如果不一致则添加背景色
                        var same = _module.commonLib.checkArrangeInArranges(arrange, _this._current.originalArranges);

                        // 构建课程安排结果渲染内容
                        var html = '<div class="mtt_arrange_item' + (same ? '' : ' mtt_arrange_item_changed') + '" draggable="true" uuid="' + arrange.uuid + '" style="height:' + height + '%">';
                        html += '       <div class="mtt_arrow_move"></div>';
                        html += '       <div>' + arrange.weekName + '</div>';
                        html += '       <div class="mtt_item_jxbmc">' + arrange.jxbmc + '</div>';
                        html += '       <div class="mtt_item_room">' + arrange.classroomName + '</div>';
                        html += '   </div>';
                        jItem.append(html);
                    }
                }
            });

            /*for (var i = 0; i < this._current.arranges.length; i++) {
                var arrange = this._current.arranges[i];
                // 对排课的结果信息添加uuid唯一标识
                if (arrange.uuid === undefined) {
                    arrange.uuid = _module.commonLib.getUuid();
                }
                // 判断当前排课结果是否与原始的结果一致，如果不一致则添加背景色
                var same = _module.commonLib.checkArrangeInArranges(arrange, this._current.originalArranges);

                var html = '<div class="mtt_arrange_item' + (same ? '' : ' mtt_arrange_item_changed') + '" draggable="true" uuid="' + arrange.uuid + '">';
                html += '       <div class="mtt_arrow_move"></div>';
                html += '       <div>' + arrange.weekName + '</div>';
                html += '       <div>' + arrange.jxbmc + '</div>';
                html += '       <div class="mtt_item_room">' + arrange.classroomName + '</div>';
                html += '   </div>';

                var jItem = _module.commonLib.findJItem(arrange.week, arrange.beginUnit, arrange.endUnit);
                if (typeof jItem === 'undefined') {
                    continue;
                }
                jItem.append(html);
            }*/
            this.bindArrageItemEvent();
        },

        /**
         * 渲染禁止排课区域
         * @param  {[type]} obstacles [description]
         * @return {[type]}           [description]
         */
        renderObstacles: function(obstacles) {
            var _this = this;
            this._current.obstacles = obstacles;

            // 先清除原有的禁排区域
            $('[data-role="item"]').each(function() {
                var jobj = $(this);
                jobj.removeAttr('title');
                jobj.removeClass('mtt_forbid');
            });

            // 渲染新的禁排区域
            $('[data-role="item"]').each(function() {
                var jobj = $(this);
                for (var i = 0; i < _this._current.obstacles.length; i++) {
                    var obstacle = _this._current.obstacles[i];
                    // 检查是否存在交叉
                    var valid = _module.conflictValidator.validateTimeObj(obstacle, {
                        weekNum: _this._current.opt.weekNum,
                        week: jobj.attr('data-week'),
                        beginUnit: jobj.attr('data-begin-unit'),
                        endUnit: jobj.attr('data-end-unit')
                    });
                    if (valid) {
                        jobj.addClass('mtt_forbid');
                        jobj.attr('title', obstacle.description || '');
                    }
                }
            });
        },

        /**
         * 设置当前选择的排课结果内容
         * @param {[type]} arrangeOrObj [description]
         */
        setSeletedArranges: function(arrangeOrObj) {
            if (this._current.selectedArranges !== undefined) {
                for (var i = 0; i < this._current.selectedArranges.length; i++) {
                    $.extend(this._current.selectedArranges[i], arrangeOrObj);
                }
                this.renderArranges();
            }
        },

        /**
         * 移除当前选择的排课结果内容
         * @return {[type]} [description]
         */
        removeSeletedArranges: function() {
            if (this._current.selectedArranges !== undefined) {
                var index = -1;
                for (var i = 0; i < this._current.arranges.length; i++) {
                    for (var j = 0; j < this._current.selectedArranges.length; j++) {
                        if (this._current.arranges[i].uuid === this._current.selectedArranges[j].uuid) {
                            this._current.arranges.splice(i, 1);
                        }
                    }
                }
                this.renderArranges();
            }
        },

        /**
         * 根据uuid找到对应的排课结果
         * @param  {[type]} uuid [description]
         * @return {[type]}      [description]
         */
        findArrange: function(uuid) {
            if (this._current.arranges !== undefined) {
                for (var i = 0; i < this._current.arranges.length; i++) {
                    if (this._current.arranges[i].uuid === uuid) {
                        return this._current.arranges[i];
                    }
                }
            }
        },

        /**
         * 根据星期、开始节次和结束节次找到对应的排课结果
         * @param  {[type]} week      [description]
         * @param  {[type]} beginUnit [description]
         * @param  {[type]} endUnit   [description]
         * @return {[type]}           [description]
         */
        findArrangesByWeekAndUnit: function(week, beginUnit, endUnit) {
            var res = [];
            if (this._current.arranges !== undefined) {
                for (var i = 0; i < this._current.arranges.length; i++) {
                    var a = this._current.arranges[i];
                    if (a.week === week && a.beginUnit <= endUnit && a.endUnit >= beginUnit) {
                        res.push(a);
                    }
                }
            }
            return res;
        },

        /**
         * 绑定排课结果安排的事件
         * @return {[type]} [description]
         */
        bindArrageItemEvent: function() {
            var _this = this;
            $('.mtt_arrange_item').dragstart(function(e) {
                _this._current.movingArrange = _this.findArrange($(this).attr('uuid'));

            }).click(function(e) {
                // 检查当前选中的排课结果的状态
                var uuid = $(this).attr('uuid');
                if ($(this).hasClass('mtt_arrange_item_selected')) {
                    $(this).removeClass('mtt_arrange_item_selected');

                    for (var i = 0; i < _this._current.selectedArranges.length; i++) {
                        if (_this._current.selectedArranges[i].uuid === uuid) {
                            _this._current.selectedArranges.splice(i, 1);
                            break;
                        }
                    }
                } else {
                    // 对当前选中的排课结果添加颜色区分
                    $(this).addClass('mtt_arrange_item_selected');

                    if (_this._current.selectedArranges === undefined) {
                        _this._current.selectedArranges = [];
                    }
                    _this._current.selectedArranges.push(_this.findArrange(uuid));
                }
            });
        },

        /**
         * 移动课程安排后调用的方法
         * @param  {[type]} movedPosition [description]
         * @return {[type]}               [description]
         */
        movedArrage: function(movedPosition) {
            // 将移动后的位置放入安排结果中
            this._current.movingArrange.week = movedPosition.week;
            this._current.movingArrange.beginUnit = movedPosition.beginUnit;
            this._current.movingArrange.endUnit = movedPosition.endUnit;

            // 开始渲染排课结果
            this.renderArranges();
        },

        /**
         * 获取星期列表
         * @param  {[type]} opt [description]
         * @return {[type]}     [description]
         */
        getWeeks: function(opt) {
            if (typeof _cache['weeks'] !== 'undefined') {
                return _cache['weeks'];
            }

            var weeks = [];
            if (opt.weeks) {
                // 如果参数带有weeks，则直接使用参数的weeks
                weeks = opt.weeks;
            } else if (opt.loadWeeksUrl) {
                // 如果参数中写了获取weeks的URL，则使用ajax获取相应的weeks
                weeks = getAjaxWeeks(opt, opt.loadWeeksUrl);
            } else {
                // 获取默认提供的weeks
                weeks = getDefaultWeeks();
            }
            _cache['weeks'] = weeks;
            return weeks;
        },

        /**
         * 获取节次列表
         * @param  {[type]} opt [description]
         * @return {[type]}     [description]
         */
        getUnits: function(opt) {
            if (typeof _cache['units'] !== 'undefined') {
                return _cache['units'];
            }

            var units = [];
            if (opt.units) {
                // 如果参数带有units，则直接使用参数的units
                units = opt.units;
            } else if (opt.loadUnitsUrl) {
                // 如果参数中写了获取units的URL，则使用ajax获取相应的units
                units = getAjaxUnits(opt, opt.loadUnitsUrl);
            } else {
                // 获取默认提供的units
                units = getDefaultUnits();
            }
            _cache['units'] = units;
            return units;
        }

    };

    function getAjaxWeeks(opt, url) {
        var _weeks = [];
        $.ajax({
            url: url,
            dataType: "json",
            type: "post",
            async: false,
            success: function(data) {
                if (opt.convertWeeksFunc) {
                    _weeks = opt.convertWeeksFunc(data);
                } else {
                    _weeks = data;
                }
            }
        });
        return _weeks;
    }

    function getDefaultWeeks() {
        return [{ code: "1", name: "星期一" }, { code: "2", name: "星期二" }, { code: "3", name: "星期三" }, { code: "4", name: "星期四" }, { code: "5", name: "星期五" }, { code: "6", name: "星期六" }, { code: "7", name: "星期日" }];
    }

    function getAjaxUnits(opt, url) {
        var _units = [];
        $.ajax({
            url: opt.loadUnitsUrl,
            dataType: "json",
            type: "post",
            async: false,
            success: function(data) {
                if (opt.convertUnitsFunc) {
                    _units = opt.convertUnitsFunc(data);
                } else {
                    _units = data;
                }
            }
        });
        return _units;
    }

    function getDefaultUnits() {
        return [{ code: "1", name: "第一节" }, { code: "2", name: "第二节" }, { code: "3", name: "第三节" }, { code: "4", name: "第四节" }, { code: "5", name: "第五节" }, { code: "6", name: "第六节" }, { code: "7", name: "第七节" }, { code: "8", name: "第八节" }, { code: "9", name: "第九节" }, { code: "10", name: "第十节" }, { code: "11", name: "第十一节" }, { code: "12", name: "第十二节" }];
    }

    return jxbTimeTable;

});
